<?php

namespace app\wechat\controller;

use think\Controller;
use think\facade\Config;
use think\facade\Url;
use think\facade\Request;
use think\facade\Cache;
use GuzzleHttp\Client;

class Index extends Controller {

  private $appId;
  private $appSecret;
  private $openId;

  // 初始化
  protected function initialize(){
    $wechatConfig = Config::pull('wechat');
    $this->appId = $wechatConfig['appId'];
    $this->appSecret = $wechatConfig['appSecret'];
  }

  public function index() {
    $redirectUrl = Url::build('getaccess', '', '', true);
    $oauthUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appId . '&redirect_uri=' . $redirectUrl . '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
    $this->redirect($oauthUrl);
    echo $redirectUrl;
  }

  public function getaccess() {
    $code = Request::get('code');
    $tokenUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->appId . '&secret=' . $this->appSecret . '&code=' . $code . '&grant_type=authorization_code';
    $client = new Client();
    $res = $client->request('GET', $tokenUrl);
    if ($res->getStatusCode() == 200){
      $resArr = json_decode($res->getBody());
      $this->openId = $resArr->openid;
      $this->redirect('register', ['openid' => $this->openId]);
    } else {
      $this->error('执行http请求失败');
    }
  }

  public function getUser(){

  }

  public function register(){
    $openId = Request::param('openid');
    $this->assign('openid', $openId);
    return $this->fetch();
  }
}